<template>
  <validate-form @form-submit="onSubmitForm">
    <div class="form-group mx-auto">
      <label for="exampleInputEmail1" class="mb-2">邮箱地址</label>
      <validate-input
        :rules="emailRule"
        type="email"
        v-model="emailValue"
        id="exampleInputEmail1"
        ref="emailInputRef"
      ></validate-input>
    </div>
    <div class="form-group">
      <label for="exampleInputPassword1" class="mb-2">密码</label>
      <validate-input
        :rules="passwordRule"
        type="password"
        v-model="passwordValue"
        id="exampleInputPassword1"
        ref="passwordInputRef"
      ></validate-input>
    </div>
  </validate-form>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import ValidateInput, { RuleProps } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import createMessage from '../hooks/createMessage'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
const emailRule: RuleProps = [
  { type: 'required', message: '邮箱不能为空' },
  { type: 'email', message: '请输入正确的邮箱格式' }
]
const passwordRule: RuleProps = [
  { type: 'required', message: '密码不能为空' },
  { type: 'password', message: '密码不能少于六位' }
]
export default defineComponent({
  components: {
    ValidateInput,
    ValidateForm
  },
  setup () {
    const router = useRouter()
    const store = useStore()
    const emailValue = ref()
    const passwordValue = ref()
    const emailInputRef = ref()
    const passwordInputRef = ref()
    const onSubmitForm = (res: boolean) => {
      if (res) {
        const payload = {
          email: emailValue.value,
          password: passwordValue.value + ''
        }
        store.dispatch('loginAndFetch', payload).then(() => {
          createMessage('登录成功 2秒后跳转到首页', 'success')
          setTimeout(() => {
            router.push('/')
          }, 2000)
        }).catch((e) => {
          console.log(e)
        })
      }
    }
    return {
      emailRule,
      emailValue,
      passwordValue,
      passwordRule,
      onSubmitForm,
      emailInputRef,
      passwordInputRef
    }
  }
})
</script>
